package owg.util.opengl;

import java.util.HashMap;

import owg.util.data.Pair;

/**Maintain a library of reserved obj model instances. Instances retrieved from this library may be shared between multiple instances, 
 * provided that they follow the contract that the models should not be changed. 
 * If they are changed in any method, they must be restored to their original state before the call returns.
 * 
 * If mutable models are required, use {@link ObjModel#getUnusedInstance(String, Armature, String, boolean)} instead.*/
public abstract class StaticModel
	{
	static final boolean DEBUG = false;
	static HashMap<String, Pair<ObjModel, Integer>> staticModels = new HashMap<String, Pair<ObjModel, Integer>>();

	/**Only call once for each user and call releaseStaticModel once after use to ensure garbage collection.*/
	public static ObjModel procureStaticModel(EGL<?> glUtil, String fileName)
		{
		Pair<ObjModel, Integer> record = staticModels.get(fileName);
		//Already loaded?
		if(record != null)
			{
			//Increment user count and return 
			record.b++;
			if(DEBUG)
				System.out.println("StaticModel: "+fileName+" now has "+record.b+" users.");
			return record.a;
			}
		//
		ObjModel m = ObjModel.getUnusedInstance(glUtil, fileName, null, null, true);
		record = new Pair<ObjModel, Integer>(m, 1);
		staticModels.put(fileName, record);
		if(DEBUG)
			System.out.println("StaticModel: "+fileName+" was loaded and has 1 user.");
		return m;
		}
	/**Only call once for each user after calling procureStaticModel to ensure garbage collection.*/
	public static void releaseStaticModel(ObjModel model)
		{
		Pair<ObjModel, Integer> record = staticModels.get(model.fname);
		if(record == null)
			{
			System.out.println("Releasing static model that has already been deleted.");
			return;
			}
		if(record.b <= 0)
			{
			System.err.println("Warning: Releasing static model with no users...");
			new Throwable().printStackTrace();
			}
		record.b--;
		if(record.b <= 0)
			{
			if(DEBUG)
				System.out.println("StaticModel: "+model.fname+" no longer has any users.");
			model.isInUse = false;
			staticModels.remove(model.fname);
			}
		else if(DEBUG)
			System.out.println("StaticModel: "+model.fname+" now has "+record.b+" users.");
		}
	/**Call to force future procures to reload the model from the {@link graphics.Model} cache, or from file.*/
	public static void removeStaticModel(String fname)
		{
		staticModels.remove(fname);
		if(DEBUG)
			System.out.println("StaticModel: "+fname+" removed from StaticModel cache");
		}
	}
